<!-- Api 权限管理 -->
<template>
  <div class="container">
    <div ref="searchBox">
      <el-form ref="searchForm" :model="queryPrams">
        <SearchArea
          :listUrl="pageUrl.list"
          @ok="getListData(pageUrl.list)"
          @reset="handleReset(searchForm, {}, pageUrl.list)"
        >
          <el-col :span="8">
            <BaseInput
              label="创建人"
              v-model="queryPrams.apiCreateUserNmae"
              prop="apiCreateUserNmae"
              :clearable="true"
              placeholder="请输入API创建人"
            >
            </BaseInput>
          </el-col>

          <el-col :span="8">
            <BaseSelect
              label="状态"
              v-model="queryPrams.apiStatus"
              :options="[
                [true, '启用'],
                [false, '停用'],
              ]"
              prop="apiStatus"
              :clearable="true"
              placeholder="请选择API状态"
            >
            </BaseSelect>
          </el-col>
          <el-col :span="8">
            <BaseSelect
              label="权限级别"
              v-model="queryPrams.apiClass"
              :options="[
                ['4', '临时用户'],
                ['0', '普通用户'],
                ['1', '管理员'],
                ['2', '超级管理员'],
              ]"
              prop="apiClass"
              :clearable="true"
              placeholder="请选择API权限等级"
            >
            </BaseSelect>
          </el-col>
          <el-col :span="8">
            <BaseInput
              label="API名称"
              v-model="queryPrams.apiName"
              prop="apiCreateUserNmae"
              :clearable="true"
              placeholder="请输入API名称"
            >
            </BaseInput>
          </el-col>
        </SearchArea>
      </el-form>
    </div>
    <div class="list">
      <div class="actionList">
        <BaseButton :icon="Plus" @click="handleAdd">新增</BaseButton>
      </div>
      <el-table
        :data="dataSourse"
        :max-height="tableHeight"
        :border="false"
        :highlight-current-row="true"
        row-key="uid"
      >
        <el-table-column type="index" align="center" label="序号" width="80" />

        <el-table-column
          prop="apiId"
          align="center"
          label="API ID"
          width="150"
        />

        <el-table-column
          prop="apiCreateUserNmae"
          align="center"
          label="创建人"
          :show-overflow-tooltip="true"
        />

        <el-table-column
          prop="apiName"
          align="left"
          label="API 名称"
          width="150"
          :show-overflow-tooltip="true"
        />

        <el-table-column
          prop="apiDesc"
          align="left"
          label="API 简介"
          width="150"
          :show-overflow-tooltip="true"
        />

        <el-table-column
          prop="apiUserTemporary"
          align="center"
          label="临时用户"
          width="100"
        >
          <template #default="scope">
            <el-switch
              v-model="scope.row.apiUserTemporary"
              :disabled="!scope.row.apiStatus"
              active-text="开"
              inactive-text="关"
            />
          </template>
        </el-table-column>

        <el-table-column
          prop="apiUserLimit"
          align="center"
          label="用户"
          width="100px"
        >
          <template #default="scope">
            <el-switch
              v-model="scope.row.apiUserLimit"
              :disabled="!scope.row.apiStatus"
              active-text="开"
              inactive-text="关"
            />
          </template>
        </el-table-column>

        <el-table-column
          prop="apiManageLimit"
          align="center"
          label="管理"
          width="100px"
        >
          <template #default="scope">
            <el-switch
              v-model="scope.row.apiManageLimit"
              :disabled="!scope.row.apiStatus"
              active-text="开"
              inactive-text="关"
            />
          </template>
        </el-table-column>

        <el-table-column
          prop="ApiSupertubeLimit"
          align="center"
          label="超管"
          width="100px"
        >
          <template #default="scope">
            <el-switch
              v-model="scope.row.ApiSupertubeLimit"
              :disabled="!scope.row.apiStatus"
              active-text="开"
              inactive-text="关"
            />
          </template>
        </el-table-column>

        <el-table-column
          prop="apiStatus"
          align="center"
          label="状态"
          width="80px"
        >
          <template #default="scope">
            <span>{{ scope.row.apiStatus ? "启用" : "停用" }}</span>
          </template>
        </el-table-column>

        <el-table-column
          prop="apiCreateDate"
          align="center"
          label="创建时间"
          width="170"
        />

        <el-table-column fixed="right" align="center" width="280px">
          <template #header>
            <span>操作</span>
          </template>
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="small"
              type="primary"
              @click="handleUpdate(scope.row)"
              >更新权限</el-button
            >
            <el-button
              size="small"
              :color="scope.row.apiStatus ? '#f89898' : '#b3e19d'"
              style="color: white"
              @click="handleStop(scope.row)"
              >{{ scope.row.apiStatus ? "停用" : "启用" }}</el-button
            >
            <el-button size="small" type="danger" @click="handleDel(scope.row)"
              >移除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <BasePagination
        :pageSourse="pageSourse"
        :pageSizes="[10, 20, 30, 50]"
        :queryPrams="queryPrams"
        :listUrl="pageUrl.list"
        layout="total, pager, jumper, sizes"
        @onSearch="getListData(pageUrl.list)"
      >
      </BasePagination>
    </div>
    <BaseModal
      :visible="apiModalVisible"
      :title="apiModalType === 'add' ? '新增API' : '编辑API'"
      :key="uuid4()"
      :okText="apiModalType === 'add' ? '确定' : '更新'"
      width="80%"
      @handleCancel="handleCancel"
      @handleOk="handleOk"
    >
      <el-form ref="modelForm" :model="formData" :rules="rules">
        <BaseInput
          label="API 路径"
          prop="apiName"
          placeholder="请输入API访问路径"
          v-model="formData.apiName"
        ></BaseInput>
        <BaseTextArea
          label="API 描述"
          prop="apiDesc"
          placeholder="请输入API描述"
          v-model="formData.apiDesc"
        ></BaseTextArea>
        <BaseEditor
          v-model="formData.apiDoc"
          height="400px"
          placeholder="请编辑API文档..."
        ></BaseEditor>
      </el-form>
    </BaseModal>
  </div>
</template>

<script setup lang="ts" name="ApiManage">
import * as api from "@/api/index";
import { SearchArea } from "@components/FormSearch/index";
import {
  BaseInput,
  BaseSelect,
  BaseButton,
  BaseModal,
  BaseTextArea,
  BaseEditor,
} from "@components/BaseForm/index";
import type { FormInstance } from "element-plus";
import usePageListData from "@/publicTs/pageListData";
import { ref, onMounted } from "vue";
import { Plus } from "@element-plus/icons-vue";
import { ElMessage as message } from "element-plus";
import { postAction } from "@/api/request";
import { v4 as uuid4 } from "uuid";

let {
  pageSourse,
  dataSourse,
  queryPrams,
  handleReset,
  getListData,
  computedTableHeight,
} = usePageListData();
let rules = {
  apiName: [{ required: true, message: "API名称不能为空" }],
  apiDesc: [{ required: true, message: "API描述不能为空" }],
};
// 检索区表单实例
let searchForm: any = ref(null);
// form表单实例
let modelForm = ref<FormInstance>();
// 检索区元素
const searchBox: any = ref(null);

// 弹窗控制器
let apiModalVisible = ref(false);
// 弹窗页面属性
let apiModalType = ref("add");
// 弹框表单数据
let formData = ref({
  apiId: "",
  apiName: "",
  apiDesc: "",
  apiDoc: "",
});

// 列表相关API
let pageUrl = {
  list: api.admin.URL_APILIST,
  add: api.admin.URL_APIADD,
  update: api.admin.URL_APIUPDATE,
  del: api.admin.URL_APIDEL,
};

// table渲染高度
let tableHeight = ref(600);
onMounted(() => {
  // 页面挂载完成后获取列表数据
  handleReset(searchForm.value, {}, pageUrl.list);
  tableHeight.value = computedTableHeight(searchBox.value, 50);
});

// 新增API
let handleAdd = (item: objectType<any>) => {
  apiModalType.value = "add";
  apiModalVisible.value = true;
};

// 编辑API
let handleEdit = (item: any) => {
  apiModalType.value = "edit";
  apiModalVisible.value = true;
  formData.value.apiId = item.apiId;
  formData.value.apiName = item.apiName;
  formData.value.apiDesc = item.apiDesc;
  formData.value.apiDoc = item.apiDoc;
};

let handleCancel = () => {
  apiModalVisible.value = false;
  formData.value.apiId = "";
  formData.value.apiName = "";
  formData.value.apiDesc = "";
  formData.value.apiDoc = "";
};

// 新增API
let handleOk = () => {
  modelForm.value?.validate((valid: boolean) => {
    if (valid) {
      postAction(pageUrl.add, formData.value).then(
        (res: BaseResponse<boolean>) => {
          if (res.body) {
            handleCancel();
            getListData(pageUrl.list);
            message.success(res.header.message || "API 新增成功");
          }
        }
      );
    }
  });
};

// 更新API权限
let handleUpdate = (item: any) => {
  if (!item.apiStatus) {
    return message.warning("请先启用API在进行更新操作！");
  }
  postAction(pageUrl.update, item).then((res: BaseResponse<boolean>) => {
    if (res.body) {
      getListData(pageUrl.list);
      message.success(res.header.message || "API 更新成功");
    }
  });
};

// API 启用|停用
let handleStop = (item: any) => {
  let params = { ...item };
  params.apiStatus = !params.apiStatus;
  postAction(pageUrl.update, params).then((res: BaseResponse<boolean>) => {
    if (res.body) {
      getListData(pageUrl.list);
      message.success(res.header.message || "API 更新成功");
    }
  });
};

// 删除API
let handleDel = (item: any) => {
  postAction(pageUrl.del, { apiId: item.apiId }).then(
    (res: BaseResponse<boolean>) => {
      if (res.body) {
        getListData(pageUrl.list);
        message.success(res.header.message || "API 删除成功");
      }
    }
  );
};
</script>

<style lang="less" scoped>
:deep(.el-table) {
  tr {
    height: 54px;
  }
}
.container {
  width: 100%;
  padding: 0px 24px;
  box-sizing: border-box;
  .list {
    .actionList {
      display: flex;
      justify-content: right;
      padding: 8px 16px;
    }
  }
}
</style>
